<template>
  <el-upload
    class="upload-box"
    action
    :accept="accept"
    :before-upload="beforeUpload">
    <div class="img-box">
      <img v-if="imgUrl" :src="imgUrl" alt="" />
      <i class="el-icon-plus" v-else></i>
    </div>
  </el-upload>
</template>

<script>
import { fileToBase64, base64ToUrl } from '@/utils/fileConvert';
export default {
  data() {
    return {
      imgUrl: null,
      accept: '.jpg, .png, .jpeg, .JPG, .PNG, .JPEG'
    };
  },
  methods: {
    beforeUpload(file) {
      if (this.validUpload(file)) {
        this.handleChange(file);
      }
      // 阻止默认上传
      return false;
    },
    validUpload(file) {
      const fileType = file.type.replace('image/', '.');
      const isImage = this.accept.indexOf(fileType) > -1;
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isImage) {
        this.$message.error('上传头像只能是 jpg、png、jpeg 格式!');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
        return false;
      }
      return true;
    },
    handleChange(file) {
      fileToBase64(file).then(res => {
        this.imgUrl = base64ToUrl(res, file.type);
        let imgObj = {
          url: res,
          file
        };
        this.$emit('setImg', imgObj);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.upload-box {
  width: 100%;
  height: 100%;
  & > ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    .img-box {
      width: 100%;
      height: 100%;
      display: flex;
      img {
        max-width: 100%;
        max-height: 100%;
        margin: auto;
      }
      i {
        margin: auto;
        &::before {
          font-size: 50px;
          color: #fff;
        }
      }
    }
    .el-upload__input {
      display: none;
    }
  }
}
</style>
